package scau.erps.service.impl;
import java.util.Iterator;
import java.util.List;

import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.service.IdEntityService;

import scau.erps.entity.Line;
import scau.erps.entity.Material;
import scau.erps.entity.Sand;
import scau.erps.service.LineService;
import scau.erps.util.CalculateMaterial;
import scau.erps.util.CalculateQuarter;
import scau.erps.util.Trans;

/** 
 * @author  outsiders
 * 生产线实现类
 *  */
public class LineServiceImpl extends IdEntityService<Line> implements LineService {
    private static final int[] PRICE={5,10,15,24}; //购买价格（手工线、半自动、全自动、柔性线，下同）
    private static final int[] BUILDTIME={1,2,3,4}; //建设周期
    private static final int[] REMAIN={1,2,3,4};   //残值
    private static final int[] DEPRECIATION={1,2,3,5};//折旧费用
    private static final int[] SWITCHTIME={0,1,2,0}; //转产时间
    private static final int[] SWITCHCOST={0,2,6,0}; //转产费用
    private static final int[] REPAIRCOST={1,1,2,2};//维护费用
	/**
	 * 购买生产线
	 * @author  outsiders
	 */ 
	public void buyLine(int team_id, int lineNo, String product, String type) {
		Sand sand=this.dao().fetch(Sand.class, team_id);
		int id=(team_id-1)*8+lineNo;//获取主键ID
		int flag=Trans.trans(type);
		
		//更新line实体
		Line line=this.dao().fetch(Line.class, id);
		line.setProduct(product);
		line.setType(type);
		line.setInvestTime(sand.getTime());
		line.setValue(0);
		line.setIsNew(1);
		line.setStatus("在建");
		this.dao().update(line);
		
	}
	/**
	 * 更新新建生产线状态 返回本季度新建生产线支出 负数表示金钱不足
	 * @author  outsiders
	 */    
	public int[] updateBuyLine(int team_id) {
		int[] pay=new int[5];
		for(int i=0;i<=4;i++){
			pay[i]=0;
		}
		Sand sand=this.dao().fetch(Sand.class, team_id);
		List<Line> list=this.dao().query(Line.class,Cnd.where("status", "=", "在建").and("team_Id", "=", team_id));
		int cash=sand.getCash();
		//int pay=0;
		String time=sand.getTime();
		Iterator<Line> iter=list.iterator();
		while(iter.hasNext()){
		    Line line=iter.next();
			//更新已完工生产线
			String type=line.getType();
			String investTime=line.getInvestTime();
			String completeTime=CalculateQuarter.getLineCompleteTime(investTime, type);
			if (completeTime.equals(time)) {
				iter.remove();
				line.setStatus("全新");
				this.dao().update(line);
				continue;
			}
			//统计需支付建设中生产线款项
			//by:zjc  统计每种生产线的建设费用
		    int flag=Trans.trans(line.getType());
		    switch(flag){
		    case 0:pay[1]+=PRICE[flag]/BUILDTIME[flag];break;
		    case 1:pay[2]+=PRICE[flag]/BUILDTIME[flag];break;
		    case 2:pay[3]+=PRICE[flag]/BUILDTIME[flag];break;
		    case 3:pay[4]+=PRICE[flag]/BUILDTIME[flag];break;
		    }
		    pay[0]=pay[0]+PRICE[flag]/BUILDTIME[flag];
		}
		//判断当前小组是否有足够的现金
		if (pay[0]>cash) {pay[0]=cash-pay[0];return pay;}
		for (Line line:list){
            int value=line.getValue();
			//更新生产线的价值
		    int flag=Trans.trans(line.getType());
		    value=value+PRICE[flag]/BUILDTIME[flag];
		    line.setValue(value);
		    this.dao().update(line);
		}
		cash=cash-pay[0];
		sand.setCash(cash);
		this.dao().update(sand);
		return pay;
	}
	
	/**
	 * 出售生产线
	 * @author  outsiders
	 */  
	public int sellLine(int team_id, int lineNo) {  
		Sand sand=this.dao().fetch(Sand.class, team_id);
		int id=(team_id-1)*8+lineNo;//获取主键ID
		Line line=this.dao().fetch(Line.class, id);
		
		int flag=Trans.trans(line.getType());
		int remain=REMAIN[flag];
		int other=sand.getOther();
		int depreciation=sand.getDepreciation();
		int cash=sand.getCash();
		int value=line.getValue();
		
		int lose=0;
		if (value>remain) {
			lose=value-remain-DEPRECIATION[flag];
			depreciation=depreciation+DEPRECIATION[flag];
		}
		other=other+lose;
		sand.setOther(other);
		sand.setDepreciation(depreciation);
		cash=cash+remain;
		
		sand.setCash(cash);

		line.setStatus("空置");
		line.setIsNew(1);
		
		this.dao().update(sand);
		this.dao().update(line);	
		return remain;
	}
	/**
	 * 生产线转产
	 * @author  outsiders
	 */  
	public boolean switchLine(int team_id, int lineNo, String product) {
		Sand sand=this.dao().fetch(Sand.class, team_id);
		int id=(team_id-1)*8+lineNo;//获取主键ID
		int cash=sand.getCash();
		int switchFee=sand.getSwitchFee();
		String time=sand.getTime();
		Line line=this.dao().fetch(Line.class, id);
		int flag=Trans.trans(line.getType());
		
		if (flag==0||flag==3){              //该线为手工线或柔性线
			line.setProduct(product);
			line.setStatus("转产");
			line.setSwitchTime(time);
			this.dao().update(line);
			return true;
		}
		else{          //该线为半自动线或全自动线
			int pay=SWITCHCOST[flag];
			if (cash<pay) return false; //当前现金不足
			                    
			cash=cash-pay;               //更新转产线属性与盘面数据
			switchFee=switchFee+pay;
			sand.setCash(cash);
			sand.setSwitchFee(switchFee);
			line.setProduct(product);
			line.setStatus("转产");
			if (flag==1) line.setSwitchTime(CalculateQuarter.addOneQuarter(time)); //半自动线
			else         line.setSwitchTime(CalculateQuarter.addTwoQuarter(time)); //全自动线
			
			
			this.dao().update(sand);
			this.dao().update(line);
			return true;
		}	
		
	}
	/**
	 * 更新转产生产线状态 返回完成转产的生产线条数
	 * @author  outsiders
	 */  
	public int updateSwitchLine(int team_id){
		List<Line> list=this.dao().query(Line.class, Cnd.where("status", "=", "转产"));
		Sand sand=this.dao().fetch(Sand.class, team_id);
		String time=sand.getTime();
		int count=0;
		
		for (Line line: list){
			if (line.getSwitchTime().equals(time)){
				line.setStatus("空闲");
				this.dao().update(line);
				count++;
			}
		}
		
		return count;
	}
	/**
	 * 支付该年生产线维护费用 返回该小组所有生产线所消耗的维护费 负数表示当前现金不足以支付维护费
	 * @author  outsiders
	 */  
	public int repairLine(int team_id) {
		List<Line> list=this.dao().query(Line.class, Cnd.where("team_Id", "=", team_id));
		Sand sand=this.dao().fetch(Sand.class, team_id);
		int cash=sand.getCash();
		int maintenanceFee=sand.getMaintenanceFee();
		int pay=0;
		int yearNow=CalculateQuarter.getCurrentYearInt(sand.getTime());
		
		for (Line line: list){           //统计需支付的维护费
			String status=line.getStatus();
			String investTime=line.getInvestTime();
			int flag=Trans.trans(line.getType());
			if (status.equals("空置")==false){
			if (status.equals("转产")||status.equals("生产")||status.equals("空闲")||status.equals("全新")){
			    String completeTime=CalculateQuarter.getLineCompleteTime(line.getInvestTime(), line.getType()); //计算生产线完成年份
			    int yearR=CalculateQuarter.getCurrentYearInt(completeTime)+1;  //计算开始收取维护费年份
			    if (yearR<=yearNow||investTime.equals("Y0Q1")) pay=pay+REPAIRCOST[flag]; //符合收取维护费条件
		     }
			
		}
		}
		if (pay>cash) return cash-pay;           //现金不足
		
		cash=cash-pay;                            //现金充足 更新盘面数据
		maintenanceFee=maintenanceFee+pay;
		sand.setCash(cash);
		sand.setMaintenanceFee(maintenanceFee);
		this.dao().update(sand);
		return pay;
	}

	/**
	 * 计算当年的折旧费用
	 * @author  outsiders
	 */  
	public int depreciateLine(int team_id) {
		List<Line> list=this.dao().query(Line.class, Cnd.where("team_Id", "=", team_id));
		Sand sand=this.dao().fetch(Sand.class, team_id);
		int year=CalculateQuarter.getCurrentYearInt(sand.getTime());
        int depreciation=sand.getDepreciation();
        int pay=0;
        
        for (Line line: list){
			int isNew=line.getIsNew();
			String type=line.getType();
			int flag=Trans.trans(type);
			if (isNew==0) {                   //符合折旧条件
				int value=line.getValue();
				if (value>REMAIN[flag]) {                       
					value=value-DEPRECIATION[flag];   //TODO 当前数据保证任意种类线折旧4年后刚好等于残值 规则修改后代码需改
					pay=pay+DEPRECIATION[flag];
					line.setValue(value);
					this.dao().update(line);
				}
			}
        }
        
        depreciation=depreciation+pay;            //更新盘面数据
        sand.setDepreciation(depreciation);
        this.dao().update(sand);  
        return pay;
	}

	@Override
	public List<Line> getLineByTeamId(int team_id) {
		return this.dao().query(Line.class, Cnd.where("team_Id", "=", team_id));
	}
	
	public Line getLineByLineNo(int team_Id,int lineNo){
		int id=(team_Id-1)*8+lineNo;
		return this.dao().fetch(Line.class, id);
	}
	
	/**
	 * 
	 * 获取所有生产线信息
	 * @author FYJ
	 */
	public List<Line> getAllLine() {
		return this.dao().query(Line.class,null);
	}
	/**
	 * 按照小组id查找改小组的所有生产线信息
	 * @author FYJ
	 */
	public List<Line> getLine(int team_Id, String type, String status) {
		SqlExpressionGroup e1 = null;
		SqlExpressionGroup e2 = null;
		SqlExpressionGroup e3 = null;
		if(team_Id != 0){
			e1 = Cnd.exps("team_Id", "=", team_Id);			
		}
		if(type != null){
			e2 = Cnd.exps("type", "=", type);
		}
		if(status != null){
			e3 = Cnd.exps("status", "=", status);
		}
		return this.query(Cnd.where(e1).and(e2).and(e3), null);
	}
	/**
	 * 查找一条生产线
	 * @author FYJ
	 */
	public Line getLineById(int lineId) {
		return this.fetch(lineId);
	}
	/**
	 * 查找一条生产线
	 * @author FYJ
	 */
	public void updateLine(Line line) {
		this.dao().update(line);
	}
	/**
	 * @author FYJ
	 */
	public List<Line> getLineByTime(int team_Id, String time) {
		SqlExpressionGroup e1 = null;
		SqlExpressionGroup e2 = null;
		if(team_Id != 0){
			e1 = Cnd.exps("team_Id", "=", team_Id);			
		}
		if(time != null){
			e2 = Cnd.exps("investTime", "=", time);
		}
		return this.query(Cnd.where(e1).and(e2), null);
	}
	


}
